﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace SpaceEngine.Input
{
    public class InputWin : GameComponent
    {
        public MouseState mouse;
        public KeyboardState keyboard;
        Game1 game;
        Vector3 mousePosition;

        public bool mouseLeftPressed;
        public bool mouseLeftClicked;

        public InputWin(Game1 game)
            : base(game)
        {
            this.game = game;
            mouseLeftPressed = false;
            mouseLeftClicked = false;
        }

        public override void Update(GameTime gameTime)
        {
            keyboard = Keyboard.GetState();
            mouse = Mouse.GetState();
            ProjectMouse();

            // reset states
            mouseLeftClicked = false;

            // Allows the game to exit
            if (keyboard.IsKeyDown(Keys.Escape))
                game.ExitGame();

            // mouse controls
            if (mouse.LeftButton == ButtonState.Pressed)
            {
                mouseLeftPressed = true;
            }
            if (mouse.LeftButton == ButtonState.Released && mouseLeftPressed)
            {
                mouseLeftPressed = false;
                mouseLeftClicked = true;
                Console.WriteLine(mousePosition);
            }

            base.Update(gameTime);
        }

        void ProjectMouse()
        {
            Viewport vp = game.GraphicsDevice.Viewport;

            // set up a ray for projecting
            Vector3 pos1 = vp.Unproject(new Vector3(mouse.X, mouse.Y, 0), game.camera.Projection, game.camera.View, game.camera.World);
            Vector3 pos2 = vp.Unproject(new Vector3(mouse.X, mouse.Y, 1), game.camera.Projection, game.camera.View, game.camera.World);
            Vector3 dir = Vector3.Normalize(pos2 - pos1);

            // don't project if parallel with floor (avoid divide by zero error)
            if (dir.Y != 0)
            {
                mousePosition = pos1 - dir * (pos1.Y / dir.Y);
            }

            mousePosition.Y = 0;
        }

        public Vector3 MousePosition
        {
            get { return mousePosition; }
        }
    }
}
